package ynu.edu.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ynu.edu.dto.*;
import ynu.edu.entity.User;
import ynu.edu.service.UserService;

import javax.validation.Valid;

@Slf4j
@RestController
@RequestMapping("/UserController")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
        try {
            String token = userService.login(loginRequest.getUserName(), loginRequest.getPassword());
            return ResponseEntity.ok(new LoginResponse(token, "登录成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new LoginResponse(null, e.getMessage()));
        }
    }
    
    @PostMapping("/register")
    public ResponseEntity<RegisterResponse> register(@Valid @RequestBody RegisterRequest request) {
        try {
            userService.register(request);
            return ResponseEntity.ok(new RegisterResponse(true, "注册成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new RegisterResponse(false, e.getMessage()));
        }
    }

    @PostMapping("/getUserInfo")
    public ResponseEntity<?> getUserInfo(@RequestBody User params) {
        log.info("Received getUserInfo request with params: {}", params);
        try {
            if (params.getUserName() == null) {
                return ResponseEntity.badRequest().body(new CommonResponse(false, "userName不能为空"));
            }
            User user = userService.getUserByName(params.getUserName());
            return ResponseEntity.ok(new CommonResponse(true, "查询成功", UserDTO.fromUser(user)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new CommonResponse(false, e.getMessage()));
        }
    }
}
